<template>
  <div>
    <div class="search-container">
      <el-input
        v-model="protectiveName"
        placeholder="名称"
        style="width: 10%; margin-right: 20px; margin-left: 20px; "
        class="rounded-input"
      />
      <el-select
        v-model="protectiveType"
        placeholder="类型"
        style="width: 10%; margin-right: 20px;"
        class="rounded-input"
      >
        <el-option label="物理防治" value="0"></el-option>
        <el-option label="化学防治" value="1"></el-option>
        <el-option label="生物防治" value="2"></el-option>
      </el-select>
      <el-select
        v-model="identify"
        placeholder="匹配方式"
        style="width: 10%; margin-right: 20px;"
        class="rounded-input"
      >
        <el-option label="AI大模型" value="1"></el-option>
        <el-option label="本地知识库" value="0"></el-option>
      </el-select>
      <el-select
        v-model="level"
        placeholder="强度"
        style="width: 10%; margin-right: 20px;"
        class="rounded-input"
      >
        <el-option label="弱" value="0"></el-option>
        <el-option label="中" value="1"></el-option>
        <el-option label="强" value="2"></el-option>
      </el-select>
      <el-select
        v-model="createdBy"
        placeholder="创建人"
        style="width: 10%; margin-right: 20px;"
        class="rounded-input"
        filterable
      >
        <el-option
          v-for="creator in creators"
          :key="creator.id"
          :label="creator.name"
          :value="creator.id"
        />
      </el-select>
      <el-button
        type="text"
        icon="el-icon-search"
        @click="fetchData"
        style="margin-left: 0;"
      ></el-button>
      <el-button
        type="text"
        icon="el-icon-refresh"
        @click="resetSearch"
        style="margin-left: 10px;"
      ></el-button>
      <el-button
        type="primary"
        icon="el-icon-plus"
        @click="handleAddProtectiveMeasure"
        style="margin-left: 300px;"
      >
        添加防治
      </el-button>
    </div>
    <el-table :data="paginatedData" style="width: 100%">
      <el-table-column prop="rowId" label="ID" width="100"></el-table-column>
      <el-table-column prop="protectiveName" label="名称" width="180"></el-table-column>
      <el-table-column prop="protectiveType" label="类型" width="180"></el-table-column>
      <el-table-column prop="level" label="防治强度" width="180"></el-table-column>
      <el-table-column prop="identify" label="匹配方式" width="180"></el-table-column>
      <el-table-column prop="condition" label="适用场景" width="180"></el-table-column>
      <el-table-column prop="introduce" label="使用说明" width="180"></el-table-column>
      <el-table-column prop="createdBy" label="创建人" width="135"></el-table-column>
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleUpdate(scope.$index, scope.row)">更新</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
     <!-- 弹窗 -->
     <el-dialog 
      title="添加防治措施" 
      :visible.sync="dialogVisibleAdd" 
      width="50%"
      @close="cancel">
      <el-form :model="newProtectiveMeasure" label-width="120px">
        <el-form-item label="名称">
          <el-input v-model="newProtectiveMeasure.protectiveName" style="width: 80%;"></el-input>
        </el-form-item>
        <el-form-item label="类型">
          <el-radio-group v-model="newProtectiveMeasure.protectiveType">
            <el-radio label="0">物理</el-radio>
            <el-radio label="1">化学</el-radio>
            <el-radio label="2">生物</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="强度">
          <el-radio-group v-model="newProtectiveMeasure.protectiveLevel">
            <el-radio label="2">强</el-radio>
            <el-radio label="1">中</el-radio>
            <el-radio label="0">弱</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="匹配方式">
          <el-radio-group v-model="newProtectiveMeasure.identify">
            <el-radio label="1">AI大模型</el-radio>
            <el-radio label="0">本地知识库</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="适用场景">
          <el-input v-model="newProtectiveMeasure.condition" style="width: 80%;"></el-input>
        </el-form-item>
        <el-form-item label="使用说明">
          <el-input v-model="newProtectiveMeasure.introduce" type="textarea" style="width: 80%;"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="addSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 弹窗 -->
    <el-dialog title="更新防治措施" :visible.sync="dialogVisibleUpdate" width="50%">
      <el-form :model="updateProtective" label-width="120px">
        <el-form-item label="名称">
          <el-input v-model="updateProtective.protectiveName" style="width: 80%;"></el-input>
        </el-form-item>
        <el-form-item label="类型">
          <el-radio-group v-model="updateProtective.protectiveType">
            <el-radio label="0">物理</el-radio>
            <el-radio label="1">化学</el-radio>
            <el-radio label="2">生物</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="强度">
          <el-radio-group v-model="updateProtective.protectiveLevel">
            <el-radio label="2">强</el-radio>
            <el-radio label="1">中</el-radio>
            <el-radio label="0">弱</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="匹配方式">
          <el-radio-group v-model="updateProtective.identify">
            <el-radio label="1">AI大模型</el-radio>
            <el-radio label="0">本地知识库</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="适用场景">
          <el-input v-model="updateProtective.condition" style="width: 80%;"></el-input>
        </el-form-item>
        <el-form-item label="使用说明">
          <el-input v-model="updateProtective.introduce" type="textarea" style="width: 80%;"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleUpdate = false">取 消</el-button>
        <el-button type="primary" @click="updateSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { selectPage, getCreators, getById, update, deleteById, add } from '@/api/protective';

export default {
  name: 'Protect',
  data() {
    return {
      tableData: [], // 假设这是从API获取的数据
      currentPage: 1,
      pageSize: 10,
      total: 0,
      protectiveName: null,
      protectiveType: null,
      identify: null,
      level: null,
      createdBy: null,
      creators: [],
      dialogVisibleAdd: false,
      dialogVisibleUpdate: false,
      newProtectiveMeasure: {
        protectiveName: null,
        protectiveLevel: null,
        protectiveType: null, // 默认选中“强”
        identify: null, // 默认选中“AI大模型”
        condition: null,
        introduce: null
      },

      updateProtective: {
        id: '',
        protectiveName: '',
        protectiveLevel: '',
        protectiveType: '', // 默认选中“强”
        identify: '', // 默认选中“AI大模型”
        condition: '',
        introduce: ''
      }
    };
  },
  computed: {
    paginatedData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.tableData.slice(start, end).map((row,index) => ({
        ...row,
        rowId: start + index + 1
      }))
    },
  },
  created() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      const params ={
        pageNo: this.currentPage,
        pageSize: this.pageSize,
        protectiveName: this.protectiveName,
        protectiveType: this.protectiveType,
        identify: this.identify,
        level: this.level,
        createdBy: this.createdBy
      };

      // 这是一个获取数据的API调用
      selectPage(params)
        .then(response => {
          this.tableData = response.data.result;
          this.total = response.data.total;
        })
        .catch(error => {
          console.error('获取数据失败', error);
        });

        getCreators()
        .then(response => {
          this.creators = response.data;
        })
        .catch(error => {
          console.error('获取数据失败', error);
        });
    },

    handleSizeChange(newSize) {
      this.pageSize = newSize;
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
    },
    handleAddProtectiveMeasure() {
      console.log('新增防治措施');
      this.dialogVisibleAdd = true;
      // 你可以在这里打开一个对话框或者跳转到新增页面
      // this.$router.push('/protect/add'); // 假设新增页面的路由是 /protect/add
    },

    cancel(){
      this.dialogVisibleAdd = false;
      this.resetNewProtectiveMeasure();
    },
    addSubmit() {
      if (
        !this.newProtectiveMeasure.protectiveName ||
        this.newProtectiveMeasure.protectiveLevel === null ||
        this.newProtectiveMeasure.protectiveType === null ||
        this.newProtectiveMeasure.identify === null
      ) {
        this.$message({
          message: '内容不能为空',
          type: 'warning'
        });
        return;
      }
      // 提交表单逻辑
      console.log('添加防治措施', this.newProtectiveMeasure);
      // 你可以在这里调用API提交数据
      add(this.newProtectiveMeasure)
        .then(response => {
          console.log('添加成功', response);
          this.dialogVisible = false;
          if(response.code === 200){
            this.$message({
              message: "添加成功!",
              type: 'success'
            });
            this.dialogVisibleAdd = false;
            this.resetNewProtectiveMeasure();
          }else{
            this.$message({
              message: response.message,
              type: 'error'
            });
          }
          this.fetchData(); // 重新获取数据
        })
        .catch(error => {
          console.error('新增失败', error);
        });
    },
    resetNewProtectiveMeasure() {
      this.newProtectiveMeasure = {
        protectiveName: null,
        protectiveLevel: null,
        protectiveType: null, // 默认选中“强”
        identify: null, // 默认选中“AI大模型”
        condition: null,
        introduce: null
      };
    },
    handleUpdate(index, row) {
      // 实现更新逻辑
      console.log('更新', index, row);
      // 你可以在这里调用更新API
      getById(row.id)
        .then(response => {
        this.updateProtective = response.data; // 将返回的数据存储到dialogData
        this.dialogVisibleUpdate = true; // 显示对话框
        })
        .catch(error => {
          console.error('更新失败', error);
          this.$message({
              message: response.message,
              type: 'error'
          });
        });
    },

    updateSubmit() {
      // 提交表单逻辑
      console.log('新增防治措施', this.updateProtective);
      const updateParams = {
        id: this.updateProtective.id,
        protectiveLevel: this.updateProtective.protectiveLevel,
        protectiveName: this.updateProtective.protectiveName,
        protectiveType: this.updateProtective.protectiveType,
        identify: this.updateProtective.identify,
        condition: this.updateProtective.condition,
        introduce: this.updateProtective.introduce
      };

      // 你可以在这里调用API提交数据
      update(updateParams).then(response => {
        console.log('更新成功', response);
        if(response.code == 200){
          this.$message({
            message: '更新成功！',
            type: 'success'
          });
        }else{
          this.$message({
            message: response.data,
            type: 'error'
          });
        }
        this.dialogVisibleUpdate = false; // 关闭对话框
        this.fetchData(); // 重新获取数据
      }).catch(error => {
        console.error('更新失败', error);
      });
    },
    handleDelete(index, row) {
      // 实现删除逻辑
      console.log('删除', index, row);
      this.$confirm('此操作将永久删除该措施, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 实现删除逻辑
        console.log('删除', index, row);
        deleteById(row.id).then(response => {
          console.log(response)
          console.log('删除成功', response);
          if(response.code === 200){
            this.$message({
              message: "删除成功!",
              type: 'success'
            });
          }else{
            this.$message({
              message: response.message,
              type: 'error'
            });
          }
          this.fetchData(); // 重新获取数据
        }).catch(error => {
          console.error('删除失败', error);
        });
      }).catch(() => {
         // 用户点击取消
        this.$message({
          message: '已取消删除~',
          type: 'info'
        });
      })
    }, 
    resetSearch() {
      // 清空搜索框中的所有输入并恢复默认选项
      this.protectiveName = null,
      this.protectiveType = null;
      this.identify = null,
      this.level = null,
      this.createdBy = null,
      this.fetchData(); // 重新获取数据
    },
  },
};
</script>

<style scoped>
.search-container {
  margin-bottom: 20px;
  margin-top: 20px;
  display: flex;
  align-items: center;
}

.rounded-input .el-input__inner {
  border-radius: 20px;
  width: 15%;
  margin-right: 10px;
}


.rounded-input:last-child .el-input__inner {
  border-radius: 20px;
  margin-right: 10px;
}

.el-select .el-input__inner {
  border-radius: 20px;
  width: 15%;
  margin-right: 10px;
}

.el-button--text {
  padding: 0; /* 去掉按钮的内边距 */
  margin-left: 10px; /* 调整按钮的左边距 */
  font-size: 20px;
}

.monitor-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-height: 100vh; /* 确保容器至少占满整个视口高度 */
  padding: 20px;
  box-sizing: border-box;
}

.monitor-table {
  width: 100%;
  flex: 1; /* 使表格内容占据剩余空间 */
  margin-bottom: 20px;
}

.record-image {
  width: 50px;
  height: 50px;
  object-fit: cover;
}

.pagination-container {
  width: 100%;
  display: flex;
  justify-content: center;
  margin-top: 20px;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff; /* 确保背景颜色与页面一致 */
  box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
  padding: 10px;
  box-sizing: border-box;
}

.el-table {
  margin-bottom: 60px; /* 根据分页组件的高度调整这个值 */
}
</style>